import React, {Component} from 'react';
import {StyleSheet, Text, View, TextInput, Button} from 'react-native';

type Props = {};
export default class FetchDemoPage extends Component<Props> {
  constructor(props) {
    super(props);
    this.state = {
      showText: ''
    }
  }

  /**
   * 加载数据
   */
  loadData = () => {
    let url = `https://api.github.com/search/repositories?q=${this.searchKey}`;
    fetch(url) // fetch默认为GET请求
      .then(response => {
        if (response.ok) {
          return response.text();
        }
        throw new Error('服务器出现404或500错误');
      })
      .then(responseText => {
        this.setState({
          showText: responseText
        })
      })
      .catch(e => {
        this.setState({
          showText: e.toString()
        })
      })
  };

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Fetch演示</Text>
        <TextInput
          style={{height: 40, borderColor: 'gray', borderWidth: 1}}
          onChangeText={text => {
            this.searchKey = text
          }}
        />
        <Button
          title={'获取数据'}
          onPress={() => {
            this.loadData();
          }}
        />
        <Text>{this.state.showText}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  }
});
